<template>
  <div class="news">
    <section class="inner_banner">
      <div class="picture_container">
        <img src="../../images/commoncard/swiperCard/news.png" title="新闻资讯inbanner" alt="新闻资讯inbanner"
          class="inner_banner_pc">
      </div>
    </section>
    <div class="nav">
      <div class="center flex flex_column_center   flex_row_strat">
        <div class="flex item">
          <i class="iconfont icon-zhuye-copy"></i>当前位置：<a href="/" title="">首页</a><span
            class="iconfont icon-jiantou_liebiaoxiangyou_o"></span><a @click="currentLoactiongo()"
            title="关于我们">新闻资讯</a><span class="iconfont icon-jiantou_liebiaoxiangyou_o"></span><a href="javascript:;"
            :title="currentLoaction" class="active" onclick="return false">{{
            currentLoaction }}</a>
        </div>
      </div>
    </div>
    <section class="center main1 clear_float">
      <div class="inner_left">
        <div class="center">
          <div class="left ">
            <div class="left_monu">
              <div class="title">
                <p class="cn">新闻资讯</p>
                <p class="en">News</p>
              </div>
              <div class="content">
                <ul>

                  <li class="hoverTips " :class="[current.currentactive == item.industryCat ? 'active' : '']"
                    ref="letfNews" v-for="(item, index) in newsItems" :key="index" @click="getdetail(item, index)">
                    <div class="flex flex_column_center flex_row_justify stair" :title="item.title">
                      <span class="flex1">{{ item.title }}</span><i class="iconfont icon-jiantou_liebiaoxiangyou_o"></i>
                    </div>
                  </li>
                </ul>
              </div>
            </div>
            <div class="left_tel">
              <img src="@/images/commoncard/qualityTel.png" alt="/服务质量监督ad2" title="/服务质量监督ad2">
            </div>
          </div>
        </div>
      </div>

      <div class="right" id="rightContent" v-if="current.showList">
        <div class="content hoverTips">
          <div class="black flex flex_row_justify  " v-for="(item, index) in rightNewsdata" :key="index"
            :title="item.title" @click="getnewsDetail(item, index)">
            <div class="img">
              <div class="picture_container">
                <img :src="item.bgPic" :alt="item.title" :title="item.title">
              </div>
            </div>
            <div class="txt">
              <h4 class="title">{{ item.title }}</h4>
              <p class="time">发布日期：{{ item.publishDate?.slice(0, 10) }}</p>
              <p class="abstract"></p>
            </div>
          </div>
        </div>
        <!-- 加载更多 -->
        <div class="loadData hide">
          <div class="">
            <a href="javascript:;" class="loadStart active transition">加载更多</a>
            <a href="javascript:;" class="loading">正在加载中<span class="iconfont icon-jiazaizhong"></span></a>
            <a href="javascript:;" class="loadEnd">我也是有底线的~</a>
          </div>
        </div>
        <!-- 分页 -->
        <div class="paging  ">
          <el-pagination background @current-change="handlePageChange" layout="total, prev, pager, next"
            :total="current.total" :page-size=current.pageSize :current-page="current.pageNum">
          </el-pagination>

        </div>
      </div>
      <div class="right" v-if="!current.showList" id="rightContent">

        <div class="content">
          <section>
            <section v-html="showDetail.content"></section>
          </section>
          <div class="footer-list hoverTips">
            <ul>
              <li v-for="(li, index) in fileList" :key="index" @click="downloadFile(li)">
                <span class="fileName"> <i v-if="fileList" class="el-icon-s-order"></i> {{ li.fileName }}<span
                    class="iconfont icon-xiazai"></span></span>
              </li>
            </ul>

          </div>
        </div>

        <!-- 详情页切换 -->
        <div class="cut" v-if="showpages">
          <div class="mbx2 l">
            <a @click="prepage(current.currentupdown[1])"><em>上一篇 :</em>{{ current.currentupdown.status ==
              'last' ?
              '暂无' : current.currentupdown[1].title }}</a>
            <a class="a1" @click="prepage(current.currentupdown[0])"><em>下一篇 :</em>{{
              current.currentupdown[0].title }}</a>

          </div>

        </div>

      </div>
    </section>
  </div>
</template>

<script>
import { extractDateFromString } from "@/utils/methods.js"
import { config } from "@/common/config.js"
import scrollMixin from '@/mixins/scrollMixin';
// 组件 B
import { EventBus } from '../../utils/event-bus.js';
export default {
  mixins: [scrollMixin],
  data() {
    return {
      newsItems: [{
        title: '本所动态',
        industryCat: 'ZJ_BSDT'
      },
      {
        title: '行业新闻',
        industryCat: 'ZJ_HYXW'
      },
      {
        // title: '招标公告',
        title: '采购公告',
        industryCat: 'ZJ_ZBGG'
      },
      {
        title: '通知公告',
        industryCat: 'ZJ_TZGG'
      }],
      rightNewsdata: [],
      currentPage: 1,
      total: 0,
      currentleft: '',
      currentLoaction: '',
      showDetail: '',
      currentpageTitle: {
        up: '',
        next: '',
        clickindex: ''

      },
      current: {
        pageNum: 1,
        pageSize: 5,
        current: 1,
        currenttitle: '',
        total: 20,
        showList: true,
        currentactive: '',
        detailtile: '',
        currentupdown: {}

      },
      showpages: true,
      showpagesnav: true,
      currentId: ''


    }
  },
  computed: {
    fileList() {
      return  this.showDetail.attachmentList

    }
  },
  watch: {
    $route: {
      handler(newVal, oldVal) {
        // 当路由参数变化时，执行相应的操作，比如重新加载数据等
        this.current.currentactive = newVal.query.tab
        if (newVal.query.data == undefined) return

        let searchval;
        try {
          searchval = typeof newVal.query.data === 'string'
            ? JSON.parse(newVal.query.data)
            : newVal.query.data;

          this.current.currenttitle = searchval.title ? searchval.title : 0
          this.getNewsAll()
        } catch (error) {
          console.error('Failed to parse route data:', error);
          this.init()
        }
      },
      immediate: true,
      deep: true // 深度监听对象的变化
    },
  },
  async created() {
    // 设置默认标题
    document.title = '广东省中山市质量计量监督检测所';

    if (this.$route.query.data != undefined) {
      let searchval;
      try {
        // 尝试解析字符串，如果已经是对象则直接使用
        searchval = typeof this.$route.query.data === 'string'
          ? JSON.parse(this.$route.query.data)
          : this.$route.query.data;
        searchval.data.attachmentList = JSON.parse(searchval.data.attachmentList)



        if (searchval.status == 'more') {
          this.current.currentactive = searchval.tab
          this.currentleft = searchval.tab
          this.getnewsDetailwww()
        } else if (searchval.type == 'search') {
          this.getNewsAll()
          // 设置搜索页面的标题
          document.title = `${searchval.title} - 中山质检`;
        } else if (searchval.status == 'detail') {
          console.log('searchval.data==>detail', searchval.data);

          // 处理详情页面的情况
          this.current.showList = searchval.showList
          this.current.currentactive = searchval.currentactive ? searchval.currentactive : searchval.data.industryCat
          this.current.detailtile = searchval.detailtile ? searchval.detailtile : searchval.data.title
          this.showDetail = searchval.data

          const headtitle = searchval.detailtile ? searchval.detailtile : searchval.data.title
          this.currentId = searchval.data.id
          // 设置详情页面的标题
          document.title = `${headtitle}`;
          await this.getUpOrDown() // 获取上一篇下一篇
          this.$nextTick(() => [
            this.showpages = true
          ])
        } else {
          let params = searchval.content
          this.current.showList = false
          this.showDetail = { content: params }
          this.current.currentactive = searchval.industryCat
          this.showpages = true
          this.getnewsDetail(searchval.data)
        }
      } catch (error) {
        console.error('Failed to parse route data:', error);
        this.init()
      }
    } else {
      this.init()
    }
  },
  mounted() {
    console.log('mounted',);
    // if (this.$route.query.data != undefined) {
    //   if (this.$route.query.data.status == 'more') {
    //     this.current.currentactive = this.$route.query.data.tab
    //     this.currentleft = this.$route.query.data.tab
    //     this.getnewsDetailwww()
    //   } else if (this.$route.query.data.type == 'search') {

    //     this.getNewsAll()detailtile
    //   }
    //   else {
    //     let params = this.$route.query.data.content
    //     this.current.showList = false
    //     this.showDetail = { content: params }
    //     this.current.currentactive = this.$route.query.data.industryCat
    //     this.showpages = true
    //     this.getnewsDetail(this.$route.query.data)
    //   }
    // } else {
    //   this.init()
    // }

    EventBus.$on('eventName', (data) => {
      // 处理事件
      this.current.currenttitle = data.title
      this.getNewsAll()

    });

  },
  methods: {
    previewPic(code) {
      return config.url + config.prefix + '/file/previewFile?code=' + code
    },
    filePreview(code) {
      return config.url + config.prefix + '/file/downloadFile?code=' + code
    },
    init() {
      this.getNewsAll()
    },
    getNewsAll() {
      let { pageNum, pageSize, current } = this.current
      let params = {
        pageNum: pageNum,
        pageSize: pageSize,
        data: {
          tenantId: 1,
          title: this.current.currenttitle,
          hided: 0,
        },
        current: current,
      }
      let _that = this
      this.$http.post(this.$api.newApis.listEnterpriseNewsAll, params).then(res => {
        if (res.code == 200) {
          let result = []
          const objArray = res.data.list
          console.log('objArray', objArray);

          if (objArray.length > 0) {
            for (let item of objArray) {
              let detail = {}
              detail.id = item.id
              detail.title = item.title
              detail.bgPic = this.previewPic(item.bgPic)
              detail.publishDate = item.publishDate || ''
              detail.createTime = item.createTime
              detail.industryCat = item.industryCat
              detail.content = item.content
              detail.attachmentList = JSON.stringify(item.attachmentList)
              result.push(detail)
            }
          }

          this.rightNewsdata = result
          console.log('rightNewsdata', this.rightNewsdata);

          this.showpages = true
          this.current.total = res.data.total


          // this.showDetail=res.data.list

        }
      })
    },
    // 获取详情
    getnewsDetailwww() {
      let { pageNum, pageSize, current } = this.current

      let params = {
        pageNum: pageNum,
        pageSize: pageSize,
        data: {
          tenantId: 1,
          industryCat: this.currentleft && this.currentleft ? this.currentleft : this.newsItems[0].industryCat,
          hided: 0,
        },
        current: current,
      }
      let _that = this
      this.$http.post(this.$api.newApis.listEnterpriseNews, params).then(res => {
        if (res.code == 200) {
          let result = []
          const objArray = res.data.list
          this.current.total = res.data.total
          if (objArray.length > 0) {
            for (let item of objArray) {
              let detail = {}
              detail.id = item.id
              detail.title = item.title
              detail.bgPic = this.previewPic(item.bgPic)
              detail.publishDate = item.publishDate || ''
              detail.createTime = item.createTime
              detail.industryCat = item.industryCat
              detail.content = item.content
              detail.attachmentList = JSON.stringify(item.attachmentList)
              result.push(detail)
            }
          }
          console.log('2===>', result);

          this.rightNewsdata = result
          this.showpages = true
        }
      })
      this.currentleft == ''
    },
    getdetail(data, index) {
      this.gotop()
      this.showDetail = {}
      this.currentLoaction = data.title
      this.currentleft = data.industryCat
      this.current.current = 1
      this.current.pageNum = 1
      this.current.showList = true
      this.current.currentactive = data.industryCat
      this.getnewsDetailwww()

    },
    gotop() {
      window.scrollTo(0, 0)
    },
    // 页号
    handlePageChange(newPage) {

      this.current.current = newPage;
      this.current.pageNum = newPage;

      if (this.currentleft == '') {
        this.getNewsAll()
      } else {
        this.getnewsDetailwww()
      }
    },
    // 获取详情
    getnewsDetail(data) {
      console.log('data', data);

      // 构建要传递的数据对象
      const detailData = {
        status: 'detail',
        data: data,
        industryCat: data.industryCat,
        content: data.content,
        showList: false,
        currentactive: data.industryCat,
        detailtile: data.title,
        attachmentList: data.attachmentList
      };

      // 在新窗口中打开，并传递序列化的数据
      window.open(`/#/news?data=${encodeURIComponent(JSON.stringify(detailData))}`, '_blank');
    },
    getUpOrDown() {
      let params = {
        title: this.current.detailtile,
        type: this.current.currentactive,
        id: this.currentId
      }
      this.$http.get(this.$api.newApis.getUpOrDownZj, params).then(res => {
        if (res.code = 200) {
          this.current.currentupdown = res.data


        }

      })
    },
    prepage(data) {
      if (data == '' || data == undefined || data.title == '暂无') { return }
      this.current.detailtile = data.title
      this.current.industry_cat = data.industry_cat
      this.currentId = data.id
      this.showDetail = data
      document.title = data.title
      this.getUpOrDown()
    },

    // 详情跳转
    detailNaV(index) {
      if (index == this.rightNewsdata.length - 2) {
        this.currentpageTitle.clickindex = index + 1
        this.showpages = true
        this.showpagesnav = false
        this.showDetail = this.rightNewsdata[index + 1]
      } else {
        this.currentpageTitle.clickindex = index + 1
        this.showDetail = this.rightNewsdata[index + 1]
        this.showpages = true
        this.showpagesnav = true
      }


    },
    detailNaVup(data, index) {
      if (index == 0) { return }
      this.currentpageTitle.clickindex = index - 1
      this.showDetail = this.rightNewsdata[index - 1]
      this.showpagesnav = true
    },
    currentLoactiongo() {
      window.location.reload()
    },
    downloadFile(file) {
      const a = document.createElement('a');
      a.href = this.filePreview(file.fileCode)

      a.download = file.fileName; // 这里是下载时保存的文件名

      a.click(); // 模拟点击下载链接
    }
  }
}
</script>
<style scoped>
@import '@/styles/index.scss';

.paging {
  text-align: center;

  .el-pagination {
    cursor: pointer;
  }
}

.cut {
  padding: 16px;
  line-height: 28px;
}

.cut .mbx2 a:hover {
  color: #1f6cc1;
}

.footer-list {
  font-size: 16px;
  width: 100%;
  /* height: 20px; */
  line-height: 20px;
      margin-top: 20px;
  .fileName {
    width:60%;
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-decoration: underline;
  }
  .el-icon-s-order {
    margin-right: 13px;
  }
  .icon-xiazai{
        color: #246ca5;
          margin-left: 20px;
  }

  ul {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    padding: 5px 16px;

  }

  li {
    width: 100%;
        padding: 4px 0px;
    text-decoration: underline;
    color: #1f6cc1;
  }
}

#rightContent {
  min-height: 800px;
}
</style>